import 'dart:io';

import 'package:whale/helper/component/download/controller.dart';
import 'package:whale/helper/component/download/state.dart';
import 'package:whale/helper/utils/util.dart';

import '../muti_download/index.dart';
import '../muti_download/muti_download_2/index.dart';
import 'index.dart';

class DownloadDemoController extends GetxController {
  DownloadDemoController();

  final state = DownloadDemoState();

  // tap
  void handleTap(int index) {
    Get.snackbar(
      "标题",
      "消息",
    );
  }

  void anyway(DownloadModel model) {
    DownloadController().anyway(model);
  }

  void download(int index, String url) async {
    if (state.downList.where((element) => element.httpUri == url).isNotEmpty) {
      var file = DownloadController.instance.state.list
          .firstWhereOrNull((element) => element.httpUri == url);
      if (file != null) {
        anyway(file);
        return;
      }
    }
    var model = await DownloadController.instance.download(
      url,
      '第$index个文件夹',
    );
    if (model != null) {
      state.downList.add(model);
      update();
    }
  }

  void toDownload() {
    // IWindow.show(DownloadFloatProgress(), name: 'ddd');
    Get.to(() => MutiDownloadPage(), binding: MutiDownloadBinding());
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    state.urls = [
      'http://download.szzfyjzx.icu/V2rayU-64.dmg',
      'https://jixiao.inspirestar.cn/assessment/apk/assessment.apk',
      'http://download.szzfyjzx.icu/IMG_0005.mov',
    ];
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() async {
    super.onReady();

    await Future.delayed(Duration(seconds: 1));

    state.isShow.value = true;

    DownloadController.instance.state.valuesChanged.listen((p0) {
      state.downList = p0;
      update();
    });
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
